import { notFound } from 'next/navigation';
import Link from 'next/link';
import { EyeIcon } from '@heroicons/react/24/outline';
import ResponsiveLayout from "@/components/ResponsiveLayout";
import { webAPI } from "@/lib/api";
import type { Case } from "@/lib/api";
import Footer from '@/components/Footer';
import ShareButton from '@/components/ShareButton';
import '@/styles/wangeditor.css';
import { cache } from 'react';

export const dynamic = 'force-dynamic'

// 生成静态页面参数
export async function generateStaticParams() {
  try {
    const response = await webAPI.getCases({ limit: 100 });
    if (response.success) {
      return response.data.cases.map((caseItem: Case) => ({
        slug: caseItem.slug,
      }));
    }
  } catch (error) {
    console.error('生成静态参数失败:', error);
  }
  return [];
}

// 获取案例数据（使用 cache 避免重复调用）
const getCase = cache(async (slug: string): Promise<Case | null> => {
  try {
    const response = await webAPI.getCaseBySlug(slug);
    if (response.success) {
      return response.data;
    }
  } catch (error) {
    console.error('获取案例失败:', error);
  }
  return null;
});

// 生成元数据
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const caseItem = await getCase(slug);
  
  if (!caseItem) {
    return {
      title: '案例不存在',
    };
  }

  return {
    title: `${caseItem.title}`,
    description: caseItem.summary || caseItem.content.replace(/<[^>]*>/g, '').substring(0, 160),
    keywords: caseItem.tags.join(', '),
    openGraph: {
      title: caseItem.title,
      description: caseItem.summary || caseItem.content.replace(/<[^>]*>/g, '').substring(0, 160),
      type: 'article',
      publishedTime: caseItem.publishedAt,
      authors: [caseItem.author],
    },
    // 微信专用meta标签
    other: {
      'wechat:title': caseItem.title,
      'wechat:description': caseItem.summary || caseItem.content.replace(/<[^>]*>/g, '').substring(0, 160),
      'wechat:image': caseItem.coverImage || '/logo.png',
      'wechat:url': `/cases/detail/${caseItem.slug}`,
    },
  };
}

export default async function CaseDetail({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const caseItem = await getCase(slug); 
  if (!caseItem) {
    notFound();
  }

  

  return (
    <ResponsiveLayout active="cases">
      <main className="py-8">
        <div className="max-w-4xl mx-auto px-6">
          {/* Breadcrumbs */}
          <div className="text-sm text-slate-500 mb-4">
            <Link href="/" className="hover:underline">首页</Link> &gt;
            <Link href="/cases" className="hover:underline">攻略</Link>
          </div>

          {/* Case Container */}
          <div className="bg-white rounded-xl shadow-md overflow-hidden">
            
            
            <div className="p-3 md:p-8">
              {/* Header */}
              <header className="border-b border-slate-200 pb-6">
                <h1 className="text-3xl md:text-4xl font-bold text-slate-900 leading-tight">
                  {caseItem.title}
                </h1>
                
                {/* 攻略摘要 */}
                {caseItem.summary && (
                  <div className="mt-4">
                    <p className="text-lg text-slate-600 leading-relaxed">
                      {caseItem.summary}
                    </p>
                  </div>
                )}
                
                {/* Meta info */}
                <div className="mt-4 flex flex-wrap items-center text-sm text-slate-500 gap-x-4 gap-y-2">
                  <span>作者: {caseItem.author}</span>
                  {caseItem?.category?.name && (
                    <div className="flex items-center gap-x-2">
                      <span>分类:</span>
                      <span className="bg-slate-100 text-slate-600 px-2 py-0.5 rounded-full text-xs font-medium">
                        {caseItem.category.name}
                      </span>
                    </div>
                  )}
                </div>
                {/* Actions and stats */}
                <div className="mt-5 flex items-center justify-between">
                  <ShareButton 
                    title={`${caseItem.title} - AI产品之家`}
                    description={caseItem.summary || caseItem.content.replace(/<[^>]*>/g, '').substring(0, 160)}
                    imageUrl={caseItem.coverImage}
                  />
                  <div className="flex items-center space-x-4 text-sm text-slate-500">
                    <span className="flex items-center">
                      <EyeIcon className="w-4 h-4 mr-1" />
                      {caseItem.views.toLocaleString()} 次阅读
                    </span>
                  </div>
                </div>
              </header>

              {/* Main Content Body */}
              <article className="prose prose-lg max-w-none prose-slate prose-headings:text-slate-800 prose-p:text-slate-600 prose-a:text-blue-600 prose-strong:text-slate-800 prose-code:text-slate-800 prose-pre:bg-slate-100">
                <div className="w-e-text-container" dangerouslySetInnerHTML={{ __html: caseItem.content }} />
              </article>

              {/* Tags 区域已移除 */}
            </div>
          </div>
        </div>
      </main>
      <Footer />
    </ResponsiveLayout>
  );
}